﻿using HalconDotNet;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;

namespace LeaderCCSLaserUI.Models.VisionModels
{
    /// <summary>
    /// 模板识别
    /// </summary>
    public class VM_FindShapeModel : FunctionBase
    {
        public override bool Run(ref HObject ho_Image, string paramJson, ref HTuple hv_Row, ref HTuple hv_Column, ref HTuple hv_Angle, ref HTuple hv_Score, ref HObject maxRegion, ref HObject ho_SelectedRegion, ref HTuple v1, ref HTuple v2)
        {
            try
            {
                var MShapeModelParam = JsonConvert.DeserializeObject<ShapeModelParam>(paramJson);
                HOperatorSet.ReadShapeModel(MShapeModelParam.FileName, out var hv_ModelID);
                HOperatorSet.FindShapeModel(ho_Image, hv_ModelID, (new HTuple(MShapeModelParam.AngleStart)).TupleRad()
                    , (new HTuple(MShapeModelParam.AngleEnd - MShapeModelParam.AngleStart)).TupleRad(), MShapeModelParam.MinScore, 1, 0.5, "least_squares", (new HTuple(MShapeModelParam.NumLevels)).TupleConcat(
                    1), 0.75, out hv_Row, out hv_Column, out hv_Angle, out hv_Score);
                HOperatorSet.ClearShapeModel(hv_ModelID);
                if (hv_Score.Length > 0)
                {
                    HOperatorSet.ReadContourXldDxf(out var ModelContours, MShapeModelParam.FileName.Replace(".shm", ".dxf"), new HTuple(), new HTuple(), out var hv_DxfStatus);
                    HTuple HomMat2D;
                    HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_Row, hv_Column, 0, out HomMat2D);
                    HObject TransContours;
                    HOperatorSet.AffineTransContourXld(ModelContours, out ho_SelectedRegion, HomMat2D);
                    ModelContours.Dispose();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return false;
            }
           
        }
    }
}
